package com.studyweb.service.impl;

import com.studyweb.mapper.UserPointsMapper;
import com.studyweb.pojo.entity.UserPoints;
import com.studyweb.service.UserPointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户积分服务实现类
 */
@Service
public class UserPointsServiceImpl implements UserPointsService {

    @Autowired
    private UserPointsMapper userPointsMapper;

    @Override
    public UserPoints getUserPoints(Long userId) {
        UserPoints userPoints = userPointsMapper.selectByUserId(userId);
        if (userPoints == null) {
            userPoints = initUserPoints(userId);
        }
        return userPoints;
    }

    @Override
    @Transactional
    public UserPoints addPoints(Long userId, Integer points) {
        UserPoints userPoints = getUserPoints(userId);
        
        // 如果已存在积分记录，则更新积分
        if (userPoints.getId() != null) {
            userPointsMapper.addPoints(userId, points);
            // 重新获取最新的积分信息
            return userPointsMapper.selectByUserId(userId);
        } else {
            // 如果不存在积分记录，则创建新记录
            userPoints.setTotalPoints(points);
            userPoints.setAvailablePoints(points);
            userPoints.setLastUpdated(LocalDateTime.now());
            userPointsMapper.insert(userPoints);
            return userPoints;
        }
    }

    @Override
    @Transactional
    public UserPoints initUserPoints(Long userId) {
        // 检查是否已存在积分记录
        UserPoints existingPoints = userPointsMapper.selectByUserId(userId);
        if (existingPoints != null) {
            return existingPoints;
        }
        
        // 创建新的积分记录
        UserPoints userPoints = new UserPoints();
        userPoints.setUserId(userId);
        userPoints.setTotalPoints(0);
        userPoints.setAvailablePoints(0);
        userPoints.setLastUpdated(LocalDateTime.now());
        userPointsMapper.insert(userPoints);
        return userPoints;
    }
}